package com.zxz.springbootredis.interceptor;

import com.google.gson.Gson;
import com.zxz.springbootredis.utils.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.Writer;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求头获取Authorization
        String authorization = request.getHeader("Authorization");

        // 2. 以"Bearer "开头
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            writeNoAuthResponse(response, "没权限访问：Token格式错误");
            return false;
        }

        // 3. 提取Token
        String token = authorization.substring(7).trim();
        if (token.isEmpty()) {
            writeNoAuthResponse(response, "没权限访问：Token为空");
            return false;
        }

        // 4. 校验Redis中是否存在该Token
        String redisValue = stringRedisTemplate.opsForValue().get(token);
        if (redisValue == null) { // Token不存在或已过期
            writeNoAuthResponse(response, "没权限访问：Token无效或已过期");
            return false;
        }

        // 5. 校验通过
        return true;
    }

    private void writeNoAuthResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        try (Writer writer = response.getWriter()) {
            JsonResult msg = JsonResult.failed(message);
            Gson gson = new Gson();
            writer.write(gson.toJson(msg));
            writer.flush();
        }
    }
}